package com.joesem.sale.client.base

import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.jiaxing.sale.client.R
import com.joesem.sale.client.widget.dialog.LoadingDialog
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseFragment<Bind : ViewBinding> : Fragment(), UiImpl {
    companion object {
        inline fun <reified T : BaseFragment<*>> newInstance(value: Bundle? = null): T {
            return T::class.java.newInstance().apply {
                value?.let {
                    arguments = value
                }
            }
        }
    }
    private var loading: LoadingDialog? = null

    open lateinit var bind: Bind

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return initBind(inflater, container, savedInstanceState)?.root
    }

    private fun initBind(
        inflater: LayoutInflater,
        container: ViewGroup?, savedInstanceState: Bundle?,
    ): Bind? {
        try {
            this@BaseFragment::class.java.genericSuperclass.let { it ->
                val type = ((it as ParameterizedType).actualTypeArguments[0]) as Class<*>
                type.getDeclaredMethod(
                    "inflate",
                    LayoutInflater::class.java,
                    ViewGroup::class.java,
                    Boolean::class.java
                ).let {
                    bind = it.invoke(null, inflater, container, false) as Bind
                    bind.initView(savedInstanceState)
                    bind.initListener()
                    return bind
                }
            }
        } catch (e: Exception) {
            return null
        }
    }

    open fun make(msg: String) {
        bind.root.toastMake(msg)
    }

    protected abstract fun Bind.initView(savedInstanceState: Bundle?)

    protected open fun Bind.initListener() {

    }
    override fun observerIntent(intent: Any?) {
        bind.initIntent(intent)
    }

    override fun showLoading() {
        if (loading == null)
            loading = LoadingDialog(requireContext())
        loading?.show()
    }

    override fun dismissLoading() {
        loading?.dismiss()
    }

    protected open fun Bind.initIntent(intent: Any?) {

    }
    protected open fun showAnimation(bgRootView: View) {
        val animationValue =
            ObjectAnimator.ofInt(
                bgRootView,
                "backgroundColor",
                R.color.white.color(),
                R.color.blackTranslucency.color()
            )
        animationValue.duration = 400
        animationValue.setEvaluator(ArgbEvaluator())
        animationValue.start()
    }

}